import React, { useState, useEffect } from 'react';
import ProCard from '@ant-design/pro-card';
import { Input, DatePicker, message, Space, Button } from 'antd';
import { request } from 'umi';
import { nanoid } from 'nanoid';

import NewsList from './components/NewsList';

const { Search } = Input;
const { RangePicker } = DatePicker;

export default function DataIntergration() {
  const [tab, setTab] = useState('all');
  const [dataSource, setDataSource] = useState([]);
  const [originalData, setOriginalData] = useState([]);
  const [tagList, setTagList] = useState([]);
  const [dateValue, setDateValue] = useState('');
  const [messageApi, contextHolder] = message.useMessage();
  const [companyName, setCompanyName] = useState('');
  const [defaultName, setDefaultName] = useState([{ name: '欧菲光' }, { name: '科大讯飞' }]);

  const handleSearch = (value) => {
    // 获取查询日期
    const { startDate: defaultStartDate, endDate: defaultEndDate } = getDate();
    const endDate = dateValue ? dateValue[1]?.format('YYYYMMDD') : defaultEndDate;
    const startDate = dateValue ? dateValue[0]?.format('YYYYMMDD') : defaultStartDate;

    const params = {
      start_date: startDate ? startDate : '',
      end_date: endDate ? endDate : '',
      enterprise: value,
      tag: tab === 'all' ? '' : tab,
    };
    if (value == '')
      setCompanyName('请输入企业完整名称');

    console.log(params);
    // 写好了
    request('/api/da/announcements/start_date/end_date/company_name/tag', {
      method: 'get',
      params: {
        start_date: startDate ? startDate : '',
        end_date: endDate ? endDate : '',
        company_name: value,
        tag: tab === 'all' ? '' : tab,
      },
    }).then((res) => {
      console.log('查询', res.data);
      if (res.data) {
        if (res.data?.filtered_records.length && res.data?.filtered_records.length > 100) {
          // messageApi.open({ type: 'warning', content: '数据过多,只显示前100条' });
          setDataSource(res.data.filtered_records.slice(0, 101));

          let tags = res.data.filtered_records.map((item) => item.f002v);
          tags = [...new Set(tags)];
          setTagList(
            tags.map((item) => {
              return { label: item, key: item };
            }),
          );
        } else {
          setDataSource(res.data.filtered_records);
          let tags = res.data.filtered_records.map((item) => item.f002v);
          tags = [...new Set(tags)];
          setTagList(
            tags.map((item) => {
              return { label: item, key: item };
            }),
          );
        }
      } else {
        setDataSource([])
      }

    });
  };

  const handleDateChange = (value) => {
    setDateValue(value);
  };

  const getDate = () => {
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
    const day = currentDate.getDate().toString().padStart(2, '0');

    const endDate = `${year}${month}${day}`;
    // console.log(endDate);

    // 获取当前日期的时间戳
    const timestamp = currentDate.getTime();

    // 计算七天前的时间戳
    const sevenDaysAgoTimestamp = timestamp - 1 * 24 * 60 * 60 * 1000;

    // 创建一个新的Date对象，表示七天前的日期
    const sevenDaysAgoDate = new Date(sevenDaysAgoTimestamp);

    // 获取七天前的年、月、日
    const y = sevenDaysAgoDate.getFullYear();
    const m = (sevenDaysAgoDate.getMonth() + 1).toString().padStart(2, '0');
    const d = sevenDaysAgoDate.getDate().toString().padStart(2, '0');

    // 格式化日期
    const startDate = `${y}${m}${d}`;
    return { startDate, endDate };
  };

  const selectAll = () => {
    const { startDate, endDate } = getDate();
    request('/api/da/announcements/latest', {
      method: 'GET',
      params: {
        end_date: endDate,
        start_date: startDate,
      },
    })
      .then((res) => {
        console.log('success', res.data);
        setDataSource(res.data.records_list);
        setOriginalData(res.data.records_list);

        // 渲染tag
        setTagList(
          res.data.sorted_f002v_counts_dict.map((item) => {
            return { label: item, key: item };
          }),
        );
      })
      .catch((err) => {
        console.log(err);
      });
  }



  useEffect(() => {
    // console.log(startDate);
    //http://115.156.114.150:16788






    const company = sessionStorage.getItem('comName');
    if (company?.length > 0) {
      setCompanyName(company)
      handleSearch(company);
      sessionStorage.setItem('comName', '');
    } else {
      selectAll();
    }
  }, []);




  return (
    <div>
      <ProCard
        title={<b style={{ fontSize: '18px' }}>数据汇聚</b>}
        layout="center"
        style={{
          borderRadius: '8px',
          marginBottom: '1em',
          marginTop: '-1em',
          height: '245px'
        }}
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <ProCard
          bodyStyle={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'column',

          }}
          className='sz-card'
        >
          <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
            <RangePicker onChange={handleDateChange} value={dateValue} style={{ margin: '0 20px' }} />

            <Search
              enterButton="查询"
              onSearch={handleSearch}
              allowClear
              style={{ width: '30%', margin: '0 30px' }}
              placeholder={companyName ? companyName : '请输入企业完整名称或简称'}
            //   onChange={onChange}
            //   value={value}
            />
          </div>

          <Space style={{ color: '#999999', marginTop: '10px' }} >
            搜索建议:
            {defaultName?.map((defaultName) => (
              <Button
                key={nanoid()}
                onClick={() => {
                  handleSearch(defaultName.name);
                  setCompanyName(defaultName.name);

                }}
                style={{ backgroundColor: '#F7F7F7', color: '#999999' }}
              >
                {defaultName.name}
              </Button>
            ))}
          </Space>
        </ProCard>

        <ProCard
          style={{ padding: '0' }}
          bodyStyle={{ padding: 0 }}
          tabs={{
            centered: 'true',
            tabPosition: 'bottom',
            activeKey: tab,
            items: [{ label: '全部', key: 'all' }, ...tagList],
            onChange: (key) => {
              setTab(key);
            },
          }}
        />
      </ProCard>

      <ProCard title={<b style={{ fontSize: '18px' }}>全部资讯</b>}>
        <NewsList dataSource={dataSource} />
      </ProCard>
    </div>
  );
}


